package com.qipay.api.home.controller;

import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.security.jwt.JWTUser;
import com.qipay.utils.ResultUtils;
import com.qipay.utils.XmlUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/")
public class HomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public JWTUser getLoginUser(
            @AuthenticationPrincipal JWTUser user
    ) {
        return user;
    }

    @RequestMapping(value = "/403", method = {RequestMethod.GET, RequestMethod.POST},
            produces={"application/xml;charset=UTF-8"})
    public String badRequest(HttpServletResponse response) {
        Map<String, Object> result = ResultUtils.createStatusResult(ApiStatusEnum.UNAUTHENTICATION.getCode().toString(),
                "请先登录");
        response.setStatus(HttpStatus.OK.value());
        try {
            return XmlUtils.toString(result, "xml");
        } catch (IOException e) {
            e.printStackTrace();
            return "<xml>\n" +
                    "<status>" + ApiStatusEnum.UNAUTHENTICATION.getCode().toString() + "</status>\n" +
                    "<message><![CDATA[SYSERR]]></message>\n" +
                    "</xml>";
        }
    }

    @RequestMapping(value = "/500", method = {RequestMethod.GET, RequestMethod.POST},
            produces={"application/xml;charset=UTF-8"})
    public String systemErr(HttpServletResponse response) {
        Map<String, Object> result = ResultUtils.createStatusResult(ApiStatusEnum.SERVICE_ERR.getCode().toString(),
                "系统错误");
        response.setStatus(HttpStatus.OK.value());
        try {
            return XmlUtils.toString(result, "xml");
        } catch (IOException e) {
            e.printStackTrace();
            return "<xml>\n" +
                    "<status>" + ApiStatusEnum.SERVICE_ERR.getCode().toString() + "</status>\n" +
                    "<message><![CDATA[SYSERR]]></message>\n" +
                    "</xml>";
        }
    }

}
